package com.supreme.threadserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.commonentity.mysql.primary.SysRole;
import com.supreme.commonmybatis.mapper.RoleMapper;
import com.supreme.commonmybatis.mapper.SupremeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "mysql")
public class MysqlController {

    @Resource
    private SupremeMapper<JSONObject> supremeMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private RoleMapper roleMapper;

    @GetMapping(value = "simpleQuery1")
    public AjaxResp simpleQuery1() {
        List<JSONObject> objectList = supremeMapper.nativeSql("select * from test");
        return AjaxResp.instance(objectList);
    }

    @GetMapping(value = "simpleQuery2")
    public AjaxResp simpleQuery2() {
        StringBuilder nativeSql = new StringBuilder("select * from test").append(" limit {0},{1}");
        List<Map<String, Object>> mapList = SqlRunner.db().selectList(nativeSql.toString(), 0, 100);
        return AjaxResp.instance(mapList);
    }

    @PostMapping(value = "createRole")
    public AjaxResp createRole(@RequestBody SysRole role) {
        int result = 0;
        try {
            result = roleMapper.insert(role);
        } catch (Exception e) {
            log.error("errorName = {} errorMessage = [{}]", e.getClass().getName(), e.getMessage());
        }
        return AjaxResp.instance(result);
    }

    @GetMapping(value = "selectRole")
    public AjaxResp selectRole() {
        List<SysRole> roleList = roleMapper.selectList(
                Wrappers.lambdaQuery(SysRole.class).ne(SysRole::getRoleDesc, "").isNotNull(SysRole::getRoleDesc)
        );
        return AjaxResp.instance(roleList);
    }
}
